/**
Workerman Net Server
内网穿透服务端
*/
<?php
use Workerman\Worker;
use Channel\Server;
use Channel\Client;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/../vendor/autoload.php';
$config = [
    //广播服务端
    'CannelIp'      =>  "0.0.0.0",
    //广播服务端端口
    'CannelPort'    =>  2206,
    //对外提供http服务的本地IP
    'LocaHost'      =>  "0.0.0.0",
    //对外提供http服务的本地端口
    'LocaHostProt'  =>  80
];

//创建广播服务端
$channel_server = new Server($config['CannelIp'],$config['CannelPort']);

//对外http服务
$workertcp = new Worker('tcp://'.$config['CannelIp'].':'.$config['‘LocaHostProt’']);

$workertcp->onWorkerStart = function($workertcp)use($config)
{
    // Channel客户端连接到Channel服务端
    Client::connect($config['CannelIp'],$config['CannelPort']);
    
    //【穿透客户端发送数据给用户】
    // 订阅OnSendMsgToUser事件，并注册事件回调
    Client::on('OnSendMsgToUser', function($event_data)use($workertcp){
        print_r($event_data);
        // 向当前worker进程的所有客户端广播消息
        foreach($workertcp->connections as $connection)
        {
            if($connection->id == $event_data['user']){
                $connection->send($event_data['body']);
            }
            
        }
    });
    
};

//用户端连接上后获取数，推送给穿透客户端
$workertcp->onMessage = function(TcpConnection $connection, $TcpData)
{
    $domain = "";
    preg_match('/Host:\s*(.*?)\r?\n/', $TcpData, $matches);
    if (!empty($matches[1])) {
        $host = trim($matches[1]);
        // 分割端口（可选）
        $parts = explode(':', $host, 2);
        $domain = $parts[0]; // 结果：net1.wlot.top
    }
    //拼接指定参数
    $data = [
        "user"=>$connection->id,
        "body"=>$TcpData
    ];
    if($domain){
        //print_r($data);//$domain
        Client::publish($domain, $data);
    }else{
        $connection->close();
    }
    
    
};

// 运行worker
Worker::runAll();
